﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Security;
using YmtRpc.Domain;

namespace YmtRpc.Web.Admin.Service
{
    public class AuthenticationService
    {
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="inputString">密码明文</param>
        /// <returns></returns>
        public  string CreateMd5(string inputString)
        {
            StringBuilder hash = new StringBuilder();
            MD5 md5 = MD5.Create();

            md5.ComputeHash(Encoding.UTF8.GetBytes(inputString))
                  .ToList()
                  .ForEach(b => hash.AppendFormat("{0:x2}", b));

            return hash.ToString();
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="loginId">用户登录名</param>
        /// <param name="password">登录密码</param>
        /// <param name="options">可选参数，方便扩展</param>
        /// <returns></returns>
        public bool Login(string loginId, string password, IDictionary options)
        {
            string pwd = ConfigurationManager.AppSettings["Password"];
            if (loginId=="rpcadmin" && CreateMd5(password) == pwd)
            {
                bool isSave = false;
                if (options != null && options.Contains("isSave"))
                {
                    object value = options["isSave"];
                    if (value != null && value is bool)
                    {
                        isSave = (bool)value;
                    }
                }
                FormsAuthentication.SetAuthCookie(loginId, isSave);
                var httpCookie = HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName];
                if (httpCookie != null)
                    httpCookie.Domain = FormsAuthentication.CookieDomain;
                return true;
            }
            return false;
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        public void Logoff()
        {
            FormsAuthentication.SignOut();
        }

    }
}